import router, { asyncRoutes, constantRoutes } from '@/router';
import { getMenus } from '@/api/system/user';
import Layout from '@/layout';

function matchComponent(path) {
  if (path.indexOf('middle-menu') >= 0) {
    path = '/middle-menu';
  }
  for (let j = 0; j < asyncRoutes.length; j++) {
    if (asyncRoutes[j].path === path) {
      return asyncRoutes[j].component;
    }
  }
  return null;
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes routes
 */
function filterAsyncRoutes(routes) {
  const res = [];
  routes.forEach(route => {
    // 一级时候的处理 以及递归到最后时候的处理
    if (route.parentId === 0 && route.children.length === 0) {
      route.component = matchComponent(route.path);
      const tempRoute = {
        path: route.path,
        component: Layout,
        children: [
          {
            path: route.path,
            component: matchComponent(route.path),
            name: route.name,
            meta: route.meta
          }
        ]
      };
      res.push(tempRoute);
      return;
    }
    if (route.component === 'Layout') {
      route.component = Layout;
    } else {
      // 匹配组件
      route.component = matchComponent(route.path);
    }
    if (route.children && route.children.length > 0) {
      filterAsyncRoutes(route.children);
    }
    res.push(route);
  });

  return res;
}

const state = {
  routes: [],
  addRoutes: []
};

const mutations = {
  SET_ROUTES: (state, asyncRoutes) => {
    router.addRoutes(asyncRoutes);
    router.options.routes = constantRoutes.concat(asyncRoutes);
    state.addRoutes = asyncRoutes;
    state.routes = constantRoutes.concat(asyncRoutes);
  }
};

const actions = {
  // 生成路由
  generateRoutes({ commit }) {
    return new Promise((resolve, reject) => {
      getMenus().then(res => {
        const menus = res.data.data.menus;
        console.log('api=获取个人菜单', res.data);
        if (menus.length === 0) {
          return reject({ code: 500, message: '异常: 获取用户菜单为空' });
        }
        commit('SET_ROUTES', filterAsyncRoutes(menus));
        resolve(menus);
      });
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
